<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace app\admin\exception;

use Illuminate\Validation\ValidationException;
use support\exception\Handler;
use support\exception\HttpException;
use Webman\Http\Request;
use Webman\Http\Response;
use Throwable;

/**
 * Class Handler
 * @package support\exception
 */
class AdminHandler extends Handler
{
    /**
     * 不用记录日志的异常
     * @var string[]
     */
    public $dontReport = [
        HttpException::class,
        AdminException::class,
        ValidationException::class
    ];

    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render(Request $request, Throwable $exception) : Response
    {
        if (method_exists($exception, 'render')) {
            $res = $exception->render($request);
            if ($res !== null) {
                return $res;
            }
        }
        if ($exception instanceof ValidationException) {
            // 判断是否为ajax请求
            if ($request->expectsJson()) {
                $json = [
                    'code' => 400,
                    'data' => [],
                    'msg' => $exception->validator->errors()->first()
                ];
                if ($this->_debug) {
                    $json['traces'] =  $exception->validator->getMessageBag();
                }
                return json($json);
            }
        }
        return parent::render($request, $exception);
    }

}
